using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MalwareMultiScan.Backends.Interfaces;

namespace MalwareMultiScan.Backends.Backends.Abstracts
{
    /// <inheritdoc />
    [ExcludeFromCodeCoverage]
    public abstract class AbstractScanBackend : IScanBackend
    {
        /// <inheritdoc />
        public abstract string Id { get; }

        /// <inheritdoc />
        public abstract Task<string[]> ScanAsync(string path, CancellationToken cancellationToken);

        /// <inheritdoc />
        public async Task<string[]> ScanAsync(Uri uri, CancellationToken cancellationToken)
        {
            using var httpClient = new HttpClient();

            await using var uriStream = await httpClient.GetStreamAsync(uri);

            return await ScanAsync(uriStream, cancellationToken);
        }

        /// <inheritdoc />
        public async Task<string[]> ScanAsync(Stream stream, CancellationToken cancellationToken)
        {
            var tempFile = Path.GetTempFileName();

            try
            {
                await using (var tempFileStream = File.OpenWrite(tempFile))
                {
                    await stream.CopyToAsync(tempFileStream, cancellationToken);
                }

                return await ScanAsync(tempFile, cancellationToken);
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
    }
}